<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\PostComment;
use app\model\PostModel;
use app\model\UserModel;
use think\facade\Db;
use think\Request;

class Post extends Base
{
    //获取所有帖子信息数据（用户端 审核通过的）
    public function getAllPostInfo(Request $request)
    {
//        $json  = array();
//        return PeeModel::getAllPeeInfo();

//        parent::initialize();

//具体帖子类别   -1是全部
        $post_category= $request->param('post_category');

        $db=new PostModel();


        if($post_category==-1)
        {
            $info = $db->table('post a,user b')
                ->where('a.user_id=b.user_id')
                ->where('a.post_check',1)
                ->order('a.post_time','desc')
                ->select();

            $total=$db->table('post a,user b')
                      ->where('a.user_id=b.user_id')
                      ->where('a.post_check',1)
                      ->count('a.post_id');
        }
        else{

            $info = $db->table('post a,user b')
                ->where('post_category',$post_category)
                ->where('a.user_id=b.user_id')
                ->where('a.post_check',1)
                ->order('a.post_time','desc')
                ->select();

            $total=$db->table('post a,user b')
                ->where('post_category',$post_category)
                ->where('a.user_id=b.user_id')
                ->where('a.post_check',1)
                ->count('a.post_id');

        }

        return json(['code'=>1,'data'=>$info,'total'=>$total]);
    }

//    获取所有帖子信息数据（管理员端 所有）
    public function getAllPostInfoByAdmin(Request $request){

        $db=new PostModel();

//        计算评论数
        $info=Db::table('post')
            ->alias('a')
            ->leftJoin('post_comment b','a.post_id = b.post_id')
            ->join('user c','a.user_id = c.user_id')
            ->field('a.post_id,a.post_title,a.post_content,a.post_category,a.post_label,a.post_time,a.post_check,a.user_id,a.post_img,c.user_name,count(b.post_id) as cnt')
            ->order('a.post_time','desc')
            ->group('a.post_id')
            ->select();


        $total=$db->table('post a,user b')
            ->where('a.user_id=b.user_id')
            ->count('a.post_id');


        return json(['code'=>1,'data'=>$info,'total'=>$total]);

    }

//    获取最新五个帖子(交流讨论社区)
    public function getNewPostInfo(Request $request)
    {
        $page= $request->param('page');
        $limit= $request->param('limit');
        $db=new PostModel();

        $info = $db->table('post a,user b')
                ->where('a.post_check',1)
                ->where('a.user_id=b.user_id')
                ->order('post_time','desc')
                ->page($page)->limit($limit)->select();

        $high_post_info=$info = $db->table('post a,user b')
            ->where('a.post_check',1)
            ->where('a.user_id=b.user_id')
            ->order('post_ctr','desc')
            ->page($page)->limit($limit)->select();

        return json(['code'=>1,'data'=>$info,'high_post_info'=>$high_post_info]);

    }

    //    获取最新五个帖子(主页)
    public function getMainNewPostInfo(Request $request)
    {
        $page= $request->param('page');
        $limit= $request->param('limit');
        $db=new PostModel();

        $all_post = $db->table('post a,user b')
            ->where('a.post_check',1)
            ->where('a.user_id=b.user_id')
            ->order('post_time','desc')
            ->page($page)->limit($limit)->select();

        $question_post = $db->table('post a,user b')
            ->where('a.post_category',1)
            ->where('a.post_check',1)
            ->where('a.user_id=b.user_id')
            ->order('post_time','desc')
            ->page($page)->limit($limit)->select();


        $experience_post = $db->table('post a,user b')
            ->where('a.post_category',2)
            ->where('a.post_check',1)
            ->where('a.user_id=b.user_id')
            ->order('post_time','desc')
            ->page($page)->limit($limit)->select();

        $life_post = $db->table('post a,user b')
            ->where('a.post_category',3)
            ->where('a.post_check',1)
            ->where('a.user_id=b.user_id')
            ->order('post_time','desc')
            ->page($page)->limit($limit)->select();

        return json(['code'=>1,'all_post'=>$all_post,'question_post'=>$question_post,
            'experience_post'=>$experience_post,'life_post'=>$life_post]);

    }

    // 根据post_id获取帖子信息
    public function getPostInfoByPostID(Request $request){

        $post_id=$request->param('post_id');

        $db=new PostModel();
        $post= $db->table('post a,user b')
            ->where('a.user_id = b.user_id')
            ->where('a.post_id',$post_id)
            ->find();

        return json($post);

    }

//    根据帖子id获取帖子评论
    public function getCommentInfoByPostID(Request $request){

        $post_id=$request->param('post_id');
//        $page= $request->param('page');
//        $limit= $request->param('limit');

        $db=new PostComment();

        $post_comment=$db->table('post_comment a,user b')
            ->where('a.post_id',$post_id)
            ->where('a.user_id = b.user_id')
            ->select();

        $total=$db->table('post_comment a,user b')
            ->where('a.post_id',$post_id)
            ->where('a.user_id = b.user_id')
            ->count('a.post_comment_id');

        return json(['code'=>1,'data'=>$post_comment,'total'=>$total]);

    }
//    添加帖子
    public function addPost(Request $request){

        // 占坑：验证token
        $user_id=UserModel::getUseridByToken($_POST['user_token']); //获取用户id
        $post_title=$_POST['post_title'];
        $post_content=$_POST['post_content'];
        $post_category=$_POST['post_category'];
        $post_label=$_POST['post_label'];
//        没有上传图片
        if($_POST['if_img']==0){
            $idle_item_img=null;
        }
        else{
            //上传图片文件
            $idle_img=$_FILES['post_img'];
            //将图片存入目录
            $dir_img = FILEDIR.'post_img/'.$user_id;

            if(!is_dir($dir_img))
            {
                mkdir($dir_img, 0777, true);
                chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
            }
            else{
                chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
            }

            // 接收图片文件信息
            $img_name = $idle_img['name'];

            $img_tmp_name = $idle_img['tmp_name']; //储存的临时文件名，一般是系统默认
            $img_ext = pathinfo($img_name, PATHINFO_EXTENSION); // 提取上传文件的扩展名
            // 得到唯一的文件名，防止因文件名相同而产生覆盖
            $idle_item_img = md5(uniqid('',true)).".$img_ext"; // md5加密，uniqid产生唯一id，microtime作前缀
            // 目标存放文件地址
            $img_destination = $dir_img."/".$idle_item_img;
            // 当文件上传成功时，存入临时文件夹，服务器开始判断
            if (@move_uploaded_file($img_tmp_name, $img_destination))
            {
//            @错误抑制符，不让用户看到警告
            }
            else {
                //echo "文件".$img_tmp_name."上传失败！";
                //返回消息
                return json(array(
                    'code' => 0
                ));
            }
            chmod($img_destination, 0777); // 修改文件模式，所有人都有读、写、执行权限
        }

        $data = [
            'post_title' => $post_title,
            'post_content' => $post_content,
            'post_category' => $post_category,
            'post_label' => $post_label,
            'user_id' => $user_id,
            'post_img' => $idle_item_img,


        ];

        $db=new PostModel();
        if ($db->save($data)) {
            //返回消息 上传成功
            return json(array(
                'code' => 1
            ));
        }
        else {
            //返回消息
            return json(array(
                'code' => 0
            ));
        }



    }

//    根据帖子id修改帖子
    public function updatePost(Request $request){

        $form=$request->param('form');

        $post_id=$request->param('post_id');

        $post=PostModel::find($post_id);

        $form['post_check']=0;
        $form['post_time']= date('Y-m-d H:i:s');

        if($post->save($form)){

            return json(['code'=>1]);
        }

        return json(['code'=>0]);

    }

//    增加阅读量
    public function addPostCtrByID(Request $request){

        $post_id=$request->param('post_id');
        $post_ctr=$request->param('post_ctr');
        $post=PostModel::find($post_id);

        $data=['post_ctr'=>$post_ctr];
        if($post->save($data)){
            return json(['code'=>1]);
        }

        return json(['code'=>0]);


    }

//    获取当前登录用户 发布的帖子（所有）
    public function getMyPostInfo(Request $request){
        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $db=new PostModel();

        $info = $db->table('post')
            ->where('user_id',$user_id)
            ->order('post_time','desc')
            ->select();

        $total=$db->table('post')
            ->where('user_id',$user_id)
            ->order('post_time','desc')
            ->count('post_id');

        return json(['code'=>1,'data'=>$info,'total'=>$total]);

    }

//    根据帖子id删除帖子
    public function deletePost(Request $request){

        $post_ids= $request->param('post_id');

        // 批量删除
        if(is_array($post_ids)){

            foreach ($post_ids as $ids){
                $post = PostModel::find($ids);
                $post_img=$post['post_img'];
                $user_id=$post['user_id'];
                $post_img_url= FILEDIR.'post_img/'.$user_id.'/'.$post_img;
                if($post->delete()){
                    if($post_img != 'default_post_img.jpg'){
                        if( unlink($post_img_url)) {}
                    }
                }
                else{
                    return json(array(
                        'code' => 0
                    ));
                }
            }
            return json(array(
                'code' =>1
            ));

        }
        else{
            $post = PostModel::find($post_ids);
            $post_img=$post['post_img'];
            $user_id=$post['user_id'];
            $post_img_url= FILEDIR.'post_img/'.$user_id.'/'.$post_img;

            if($post->delete()){
                if($post_img != 'default_post_img.jpg'){
                    if( unlink($post_img_url))
                    {
                        //返回消息
                        return json(array(
                            'code' => 1
                        ));
                    }
                }
                else
                {
                    return json(array(
                        'code' => 1
                    ));
                }

            }

            return json(array(
                'code' => 0
            ));
        }

    }

//    获取当前登录用户所评论的帖子以及相应评论
    public function getMyPostComment(Request $request){

        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $page= $request->param('page');
        $limit= $request->param('limit');
        $db=new PostComment();

        $info = $db->table('post a,post_comment b,user c')
            ->where('c.user_id',$user_id)
            ->where('a.post_id = b.post_id')
            ->where('b.user_id = c.user_id')
            ->order('b.post_comment_time','desc')
            ->page($page)->limit($limit)->select();

        $total=$db->table('post a,post_comment b,user c')
            ->where('c.user_id',$user_id)
            ->where('a.post_id = b.post_id')
            ->where('b.user_id = c.user_id')
            ->order('b.post_comment_time','desc')
            ->count('b.post_comment_id');

        return json(['code'=>1,'data'=>$info,'total'=>$total]);

    }

//    根据帖子评论id删除评论
    public function deletePostComment(Request $request){

        $post_comment_ids= $request->param('post_comment_id');

        $post=new PostComment();

        //判断id是数组还是一个数值
        if(is_array($post_comment_ids)){
            $condition = 'post_comment_id in('.implode(',',$post_comment_ids).')';
        }else{
            $condition = 'post_comment_id='.$post_comment_ids;
        }

        if($post->where($condition)->delete()){
            return json(['code'=>1]);
        }

        return json(['code'=>0]);

    }

//    根据post_comment_id修改帖子评论内容
    public function updatePostComment(Request $request){

        $post_comment_id= $request->param('post_comment_id');
        $post_comment_content=$request->param('post_comment_content');

        $post_comment= PostComment::find($post_comment_id);

        $data=['post_comment_content'=>$post_comment_content];

        if($post_comment->save($data)){

            return json(['code'=>1]);
        }
        return json(['code'=>0]);

    }

//    根据post_id发表评论
    public function addPostComment(Request $request){

        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id
        $post_id=$request->param('post_id');
        $post_comment_content=$request->param('post_comment_content');

        $post_comment=new PostComment();
        $data = ['post_id'=>$post_id,'post_comment_content'=>$post_comment_content,'user_id'=>$user_id];


        if($post_comment->save($data))
        {
            return json(['code'=>1]);
        }

        return json(['code'=>0]);

    }

//根据post_id修改审核情况
    public function updateCheckByPostId(Request $request){

        $post_ids= $request->param('post_id');
        $post_id_check=$request->param('post_id_check');
        $data=['post_check' => $post_id_check];


        //批量修改
        if(is_array($post_ids)){

            foreach ($post_ids as $ids){
                $post=PostModel::find($ids);
                if($post->save($data)){
                    // 审核通过，给用户加分
                    if($post_id_check==1){
                        $user_id = $post['user_id'];
                        $user=UserModel::find($user_id);
                        $user_credit=$user['credit'];
                        $new_credit=$user_credit+5;
                        $new_data=['credit'=>$new_credit];
                        if($user->save($new_data)){}
                        else
                        {
                            return json(['code' => 0]);
                        }

                    }
                }
                else{
                    return json(['code' => 0]);
                }
            }

            return json(['code'=>1]);

        }
//        单个修改
        else{

            $post=PostModel::find($post_ids);
            if($post->save($data)){

//            审核通过，给用户加分
                if($post_id_check==1){
                    $user_id = $post['user_id'];
                    $user=UserModel::find($user_id);
                    $user_credit=$user['credit'];
                    $new_credit=$user_credit+5;
                    $new_data=['credit'=>$new_credit];
                    if($user->save($new_data)){
                        return json(['code' => 1]);
                    }
                    else
                    {
                        return json(['code' => 0]);
                    }

                }

                return json(['code'=>1]);
            }

            return json(['code'=>0]);

        }

    }

    //    获取所有帖子信息评论
    public function getAllPostComment(){

        $info=Db::name('post')
            ->alias('a')
            ->join('post_comment b','a.post_id = b.post_id')
            ->join('user c','a.user_id = c.user_id')
            ->join('user d','b.user_id = d.user_id')
            ->field('a.post_title,b.post_comment_id,
                          a.post_content,a.post_category,a.post_label,a.post_check,
                          a.post_time,c.user_name as post_user_name,
                          b.post_comment_content,b.post_comment_time,d.user_name as comment_user_name')
            ->select();


        return json(['code'=>1,'data'=>$info]);

    }

    //    获取用户帖子（通过审核的）
    public function getUserPostInfo(Request $request){
        $user_id=$request->param('user_id'); //获取用户id

        $db=new PostModel();

        $info = $db->table('post')
            ->where('user_id',$user_id)
            ->where('post_check',1)
            ->order('post_time','desc')
            ->select();

        $total=$db->table('post')
            ->where('user_id',$user_id)
            ->where('post_check',1)
            ->order('post_time','desc')
            ->count('post_id');

        return json(['code'=>1,'data'=>$info,'total'=>$total]);

    }

//    计算帖子数量
    public function getPostCnt(){

        $post=new PostModel();
//        通过审核
        $que_ok=$post->where('post_category',1)
            ->where('post_check',1)
            ->count('post_id');
        $exp_ok=$post->where('post_category',2)
            ->where('post_check',1)
            ->count('post_id');
        $life_ok=$post->where('post_category',3)
            ->where('post_check',1)
            ->count('post_id');
        $oth_ok=$post->where('post_category',4)
            ->where('post_check',1)
            ->count('post_id');
//        审核不通过
        $que_nook=$post->where('post_category',1)
            ->where('post_check',2)
            ->count('post_id');
        $exp_nook=$post->where('post_category',2)
            ->where('post_check',2)
            ->count('post_id');
        $life_nook=$post->where('post_category',3)
            ->where('post_check',2)
            ->count('post_id');
        $oth_nook=$post->where('post_category',4)
            ->where('post_check',2)
            ->count('post_id');
//        待审核
        $que=$post->where('post_category',1)
            ->where('post_check',0)
            ->count('post_id');
        $exp=$post->where('post_category',2)
            ->where('post_check',0)
            ->count('post_id');
        $life=$post->where('post_category',3)
            ->where('post_check',0)
            ->count('post_id');
        $oth=$post->where('post_category',4)
            ->where('post_check',0)
            ->count('post_id');

        return json(['code' => 1,'que_ok'=>$que_ok,'exp_ok'=>$exp_ok,'life_ok'=>$life_ok,'oth_ok'=>$oth_ok,
            'que_nook'=>$que_nook,'exp_nook'=>$exp_nook,'life_nook'=>$life_nook,'oth_nook'=>$oth_nook,
            'que'=>$que,'exp'=>$exp,'life'=>$life,'oth='=>$oth]);

    }


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
